<?php

namespace Redpackage\Controller;

use Think\Controller;

class IndexController extends Controller {

    public function _initialize() {
        $this->openid = wx_openid();
    }

    function index() {
        $openid = $this->openid;
        //echo $openid;exit;
        $this->assign('openid', $openid);
        $rs = check_vip2($openid); //会员基本信息
        //var_dump($rs);exit;
        if (!$rs) {
            $redirec_url = C('BASE_URL') . 'redpackage.php';
            checkFans($openid, $redirec_url);
        } else {
            $this->display();
        }
    }

    //红包抽奖页面拉取
    function loadInit() {
        $this->assign('openid', $this->openid);
        $this->display('game');
    }

    //异步处理红包
    function checkCode() {
        $jsonMsg['status'] = 0;
        $code = I('code_id');
        $where['code_id'] = $code;
        $gc = M('prize_config');
        $checkcode = M('code_detail')->where($where)->find();
        if ($checkcode) {
            $hw['house'] = array('like', '%' . substr($code, 0, 3) . '%');
            $storeConf = M('prize_store')->where($hw)->find(); //查询楼盘项目配置基本信息
            if (!$storeConf) {
                $jsonMsg['info'] = '主人，新购房的业主才能领取红包哦~';
                $this->ajaxReturn($jsonMsg);
            } else {
                $data = $gc->where('sid=' . $storeConf['id'])->select(); //查询奖品list
                if (!$data) {
                    $jsonMsg['info'] = '奖品还未设置!';
                    $this->ajaxReturn($jsonMsg);
                }
            }
            $jsonMsg['status'] = 1;
            $jsonMsg['info'] = $storeConf['id']; //楼盘主键ID
        } else {
            $jsonMsg['info'] = '邀请码不正确，请重新输入~';
        }
        $this->ajaxReturn($jsonMsg);
    }
    //初始化数据
    function myprizeInfo() {
        $order = M('prize_order');
        $map['openid'] = I('openid');
       // $count = $order->where($map)->count(); //订单总数
        $orders = $order->where($map)->find();
        $starttime = '2015-11-20 00:00:00';
        $rs = check_vip2(I('openid')); //会员基本信息
        if ($orders) {
            $jsonMsg['status'] = -1;
           // $jsonMsg['info'] = "小主,您已经领过了~";
            $jsonMsg['theAward'] = $this->getPrizeName($orders['prizeid']);
            $jsonMsg['tel'] = $orders['tel'];
            $jsonMsg['name'] = $orders['name'];
            $jsonMsg['ctime'] = date('Y-m-d', strtotime($orders['ctime']));
        } else {
            //会员是否有资格
            if (date('Y-m-d', ($rs['ctime'])) < date('Y-m-d', strtotime($starttime))) {
                $jsonMsg['status'] = 0;
                $jsonMsg['info'] = '主人，新购房的业主才能领取红包哦~';
            } else {
                $jsonMsg['status'] = 1;
            }
        }
        $this->ajaxReturn($jsonMsg);
    }

    //查询奖品名
    private function getPrizeName($id) {
        return M('prize_config')->where('id=' . $id)->getField('praisename');
    }

    //刮刮卡拉取抽奖信息
    function getAjaxRedRs() {
        $gc = M('prize_config');
        $where['sid'] = $_REQUEST['sid'];
        $where['status'] = 2;
        $data = $gc->where($where)->select(); //查询奖品list
        echo $this->getResult($data, I('code_id'));
    }

    //处理中奖结果
    private function getResult($priearr, $code_id) {

        $huiyuan = check_vip2($this->openid); //会员基本信息
        $arr = array();
        $count = array();
        $tempArr = array();
        foreach ($priearr as $key => $val) {
            $arr[$val['id']] = $val['chance'];
            $count[$val['id']] = $val['praisenumber'];
        }
        foreach ($priearr as $key => $val) {
            $tempArr[$val['id']] = $priearr[$key];
        }

        $rid = $this->getRand($arr, $count); //根据概率获取奖项id
        $res = $tempArr[$rid]; //中奖项
        // print_r($res);exit;
        $order = M('prize_order');
        $mode = M('prize_config');
        $row = $mode->field(praisenumber)->where(array('id' => $res['id']))->find(); //查询奖品库存
        $mode->startTrans();
        $order->startTrans();
        if (empty($row) || $row['praisenumber'] <= 0) {
            $result['status'] = 0;
            $result['info'] = "来晚了,奖品被抢完了!";
        } else {
            $num = $row['praisenumber'] - 1;
            $prizestate = $mode->where(array('id' => $res['id']))->save(array('praisenumber' => $num)); //更新奖品数量
            $arr = array(
                'name' => $huiyuan['huiyuan_name'],
                'sid' => $res['sid'],
                'prizeid' => $res['id'],
                'openid' => $huiyuan['open_id'],
                'code_name' => $code_id,
                'tel' => $huiyuan['huiyuan_tel'],
                'cardno' => $huiyuan['card_no'],
                'ctime' => getSysTime()
            );
            $orderstate = $order->add($arr); //添加中奖纪录
            if ($orderstate && $prizestate) {
                $result['status'] = 1;
                //$result['sncode'] = $orderstate;
                $result['tel'] = $arr['tel'];
                $result['name'] = $arr['name'];
                $result['ctime'] = date('Y-m-d', strtotime($arr['ctime']));
                $result['info'] = $res['praisename'] /* . '--' . $res['praisecontent'] */;
                $mode->commit();
                $order->commit();
            } else {
                $mode->rollback();
                $order->rollback();
            }
        }
        return $this->json($result);
    }

    private function getRand($proArr, $proCount) {
        //print_r($proArr);exit;
        $result = '';
        $proSum = 0;
        //概率数组的总概率精度  获取库存不为0的
        foreach ($proCount as $key => $val) {
            //echo $proArr[$key];;
            if ($val <= 0) {
                continue;
            } else {
                $proSum = $proSum + $proArr[$key];
            }
        }

        //概率数组循环 �
        foreach ($proArr as $key => $proCur) {
            if ($proCount[$key] <= 0 || $proSum <= 0) {
                continue;
            } else {
                $randNum = mt_rand(1, $proSum); //关键
                // echo $proCur;
                if ($randNum <= $proCur) {
                    // echo $key;
                    $result = $key;
                    break;
                } else {

                    $proSum -= $proCur;
                }
            }
        }

        unset($proArr);
        return $result;
    }

    private function json($array) {
        $this->arrayRecursive($array, 'urlencode', true);
        $json = json_encode($array);
        return urldecode($json);
    }

    //对数组中所有元素做处理
    private function arrayRecursive(&$array, $function, $apply_to_keys_also = false) {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                arrayRecursive($array[$key], $function, $apply_to_keys_also);
            } else {
                $array[$key] = $function($value);
            }
            if ($apply_to_keys_also && is_string($key)) {
                $new_key = $function($key);
                if ($new_key != $key) {
                    $array[$new_key] = $array[$key];
                    unset($array[$key]);
                }
            }
        }
    }

}
